"""
File: example_1.py
Project: Develop
File Created: 2020/02/19 15:48:34
Author: Dunmore (fovd2020@outlook.com)
-------------------------------------------------------
Description:
1.3 思考与练习 基础部分
让一颗篮球在游戏窗口内高速移动，并且碰到边缘就反弹
-------------------------------------------------------
"""
import os
import pygame
from random import randint
from pygame.locals import Rect

# 获取文件所在的路径
CURRRENT_DIR = (
    os.path.dirname(__file__) if "__file__" in locals() else os.getcwd()
)

# 屏幕宽度和高度
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600

# 定义白色
WHITE = (255, 255, 255)

# 初始化pygame
pygame.init()
# 设置窗口标题
pygame.display.set_caption("碰碰球游戏")
# 创建一个Surface对象（面板，代表了在桌面上出现的那个窗口）
screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])
# 用自定义的白色填充
screen.fill(WHITE)

# 装载指定路径的图片,通过设置subsurface可以选择截取一张图片的不同区域，从而实现篮球足球的切换
# Rect((0,0),(135,135))为足球
ball = pygame.image.load(
    os.path.join(CURRRENT_DIR, "images", "ball.png")
).subsurface(Rect((135, 0), (135, 135)))

# 绘制球
ball_x = randint(0, SCREEN_WIDTH)
ball_y = randint(0, SCREEN_HEIGHT)

screen.blit(ball, (ball_x, ball_y))
pygame.display.update()

# 球在x轴方向和y轴方向运动的向量
vcotr_x = 5
vctor_y = 5


# 创建时钟对象，可以控制游戏循环频率
t = pygame.time.Clock()

# 程序是否继续运行的标志
running = True
while running:
    # 按ESC退出
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False
    # 球按照之前的方向运动
    ball_x += vcotr_x
    ball_y += vctor_y

    # 边缘检测，碰到边缘改变相应方向的向量为它的相反数实现反向运动
    if ball_x < 0:
        ball_x = 0
        vcotr_x = -vcotr_x
    if ball_x > SCREEN_WIDTH - 135:
        ball_x = SCREEN_WIDTH - 135
        vcotr_x = -vcotr_x
    if ball_y < 0:
        ball_y = 0
        vctor_y = -vctor_y
    if ball_y > SCREEN_HEIGHT - 135:
        ball_y = SCREEN_HEIGHT - 135
        vctor_y = -vctor_y

    # 重新绘制球
    screen.fill(WHITE)
    screen.blit(ball, (ball_x, ball_y))
    pygame.display.update()

    # 设置刷新频率
    t.tick(30)

# 退出
pygame.quit()
